# Monitor RAM Usage on Linux boxes using ps aux command.

# Total RAM consumed, Average RAM consume, Data Points for Each Mongrel.

import os, sys

from vyperlogix import misc
from vyperlogix.misc  import _utils
from vyperlogix.misc import ReportTheList
from vyperlogix.lists import ListWrapper

from vyperlogix.hash import lists

from vyperlogix.daemon.daemon import Log

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

_start_proc = '/usr/local/bin/mongrel_rails cluster::start -C /etc/mongrel_cluster/molten.yml --clean --only %d'

def main():
    if (sys.platform != 'win32'):
        from vyperlogix.process import Popen
        
        buf = StringIO.StringIO()
        shell = Popen.Shell(['ps aux | grep mongrel_rails'],isExit=True,isWait=True,isVerbose=True,fOut=buf)
        lines = [l for l in buf.getvalue().split('\n') if (len(l.strip()) > 0) and (l.find('grep mongrel') == -1)]
        #ReportTheList.reportTheList(lines,'ps aux',fOut=sys.stdout)
        
        _lines = [ListWrapper.ListWrapper(l.split()) for l in lines]
        #ReportTheList.reportTheList(_lines,'ps aux',fOut=sys.stdout)
        
        d = lists.HashedLists2()
        for _l in _lines:
            i = _l.findFirstContaining('-p')
            if (i > -1):
                n = int(_l[i+1])
                #print _l[i:i+2],n
                d[n] = _l
                #print '-'*40
        #print '='*40
        
        keys = misc.sortCopy(d.keys())
        
        #ReportTheList.reportTheList(d.keys(),'Present Mongrels',fOut=sys.stdout)

        d_expected = lists.HashedLists2(dict([(n,n) for n in xrange(8100,8160)]))
        for n in d.keys():
            del d_expected[n]

        commands = []
        for n in d_expected.keys():
            aCommand = _start_proc % int(n)
            commands.append(aCommand)

        if (len(commands) > 0):
            ReportTheList.reportTheList(d_expected.keys(),'Missing Mongrels',fOut=sys.stdout)
            ReportTheList.reportTheList(commands,'Commands',fOut=sys.stdout)
            
            _logPath = os.path.join(os.path.dirname(sys.argv[0]),'log')
            _utils._makeDirs(_logPath)
            fname = os.path.splitext(os.path.basename(sys.argv[0]))[0]
            fLog = open(os.path.join(_logPath,'%s_%s.log' % (fname,_utils.timeStampForFileName())),'a')
            logger = Log(fLog)
            _stdout = sys.stdout
            sys.stdout = logger
            
            try:
                buf = StringIO.StringIO()
                shell = Popen.Shell(commands,isExit=True,isWait=True,isVerbose=True,fOut=buf)
                lines = [l for l in buf.getvalue().split('\n')]
                ReportTheList.reportTheList(lines,'Restart Dead Mongrels',fOut=sys.stdout)
            finally:
                sys.stdout = _stdout
            

if (__name__ == '__main__'):
    from vyperlogix.misc import _psyco
    _psyco.importPsycoIfPossible(func=main)
    
    main()
    